package ils.domain.model;


import ils.util.Util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class UserRepositoryImpl implements UserRepository
{
    private static final String GET_USERS = "select user from User as user where user.id in (:idList)";
    private static final String LOGIN = "select user from User as user where user.email = :email and user.passwordHash = :password";
    private SessionFactory sessionFactory;
    public User createUser(User user)
    {
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
        return user;
    }

    @Override
    public Map<Integer, User> getUsers(List<Integer> userIds)
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(GET_USERS);
        query.setParameterList("idList", userIds);
        List<User> users = query.list();
        Map<Integer, User> userMap = new HashMap<Integer, User>();
        for(User user : users)
        {
            userMap.put(user.getId(), user);
        }
        return userMap;
    }

    @Override
    public User getUser(int userId)
    {
        Session session = sessionFactory.getCurrentSession();
        return (User)session.get(User.class, userId);
    }

    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public User login(String email, String password)
    {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(LOGIN);
        query.setString("email", email);
        query.setString("password", password);
        User user = (User)query.uniqueResult();
        if(user == null) throw new RuntimeException("Invalid credentials");
        return user;
    }
}
